//
//  AddEventViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/18/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "AddEventViewController.h"
#import "iBacchanal.h"
#import "StackMob.h"
#import "UIImage+Resize.h"

@implementation AddEventViewController

@synthesize scrollView;
@synthesize eventName;
@synthesize eventLocation;
@synthesize addFlyer;
@synthesize flyerFront, flyerBack;
@synthesize startDate, endDate, datePicker;
@synthesize eventNotes;




-(IBAction)selectSideOne:(UIButton *)sender{
	front = YES;
	UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
	
	imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	imagePicker.delegate = self;
	[self presentModalViewController:imagePicker animated:YES];
	[imagePicker release];
}


-(IBAction)selectSideTwo:(UIButton *)sender{
	front = NO;
	UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
	
	imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	imagePicker.delegate = self;
	[self presentModalViewController:imagePicker animated:YES];
	[imagePicker release];
}

-(IBAction)cancelSubmit:(UIBarButtonItem *)sender{
	//UIAlertView *submitAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Are you sure? Any changes not saved will be lost." delegate:self cancelButtonTitle:@"Yes, I am Sure" otherButtonTitles:@"No",nil];
	//[submitAlert show];
	//[submitAlert release];
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)submitEvent:(UIBarButtonItem *)sender{
	
	if ([[eventName text] length] == 0 ||  [[eventLocation text] length] == 0 ||[[startDate text] length] == 0 ||[[endDate text] length] == 0 ) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Please make sure all required fields are filled out"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	else{
		[self postEvent];
	}
}


-(void)postEvent{
	iBacchanal *bacchanal = [iBacchanal sharedUser];;
	
	
	bacchanal.eventFlyersArray = [[NSMutableArray alloc] init];
	
	NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:eventName.text, @"eventName", eventLocation.text,
						  @"eventLoc", eventNotes.text, @"eventNotes", startDate.text, @"eventStart",
						  endDate.text, @"eventEnd", bacchanal.currentUser, @"submittedBy", nil];
	
	[[StackMob stackmob] post:@"events" withArguments:args andCallback:^(BOOL success, id result) {
		if (success) {
			NSDictionary *eventsResult = (NSDictionary *)result;
			bacchanal.eventID = [eventsResult objectForKey:@"events_id"];
			
			// Put in the flyers now
			//NSData *photo1 = UIImagePNGRepresentation(flyerFront.image);
			//NSData *photo2 = UIImagePNGRepresentation(flyerBack.image);
			//SMFile *somePhoto1 = [SMFile fileWithName:@"flyer.png" data:photo1 contentType:@"image/png"];
			//SMFile *somePhoto2 = [SMFile fileWithName:@"flyer.png" data:photo2 contentType:@"image/png"];
			
			//NSDictionary *flyer1 = [NSDictionary dictionaryWithObjectsAndKeys:somePhoto1, @"flyer", nil];
			//NSDictionary *flyer2 = [NSDictionary dictionaryWithObjectsAndKeys:somePhoto2, @"flyer", nil];
			NSArray *fliers = [NSArray arrayWithObjects:flyerFront, flyerBack, nil];
			
			for (NSDictionary *flyer in fliers){
				
				// Check is image exists 
				
				if ([[flyer image] CGImage] != NULL){
					
					NSData *photoData = UIImagePNGRepresentation([flyer image]);
					SMFile *photoFile = [SMFile fileWithName:@"flyer.png" data:photoData contentType:@"image/png"];
					
					
					// upload fliers
					[[StackMob stackmob] post:@"fliers" withArguments:[NSDictionary dictionaryWithObjectsAndKeys:photoFile, @"flyer", nil] andCallback:^(BOOL success, id result) {
						if (success) {
							NSDictionary *resultObj = (NSDictionary *)result;
							// operation succeeded, all objects have been inserted and updated
							
							// Update events table
							[[StackMob stackmob] put:@"events" withId:bacchanal.eventID andField:@"event_fliers" andArguments:[NSArray arrayWithObjects:[resultObj objectForKey:@"fliers_id"], nil] andCallback:^(BOOL success, id result) {
								if (success) {
									// document was updated										
								} else {
									// update failed
								} 
							}];
							
						} else {
							// operation failed
							NSLog(@"Something's wrong insert fliers....%@");
						}
					}];
				}
			}
			bacchanal.dataChanged = YES;
			UIAlertView *submitAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Your event had been successfully submitted." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			submitAlert.tag = 1;
			[submitAlert show];
			//[self dismissModalViewControllerAnimated:YES];
		}
		
		else {
			// operation failed
		}
	}];	
	
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (alertView.tag == 1){
		[alertView release];
	[self dismissModalViewControllerAnimated:YES];
	}
	
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
	[[UIApplication sharedApplication] setStatusBarHidden:NO];
	[self dismissModalViewControllerAnimated:YES];
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	if (front){
		bacchanal.flyerSideOne = [[info objectForKey:UIImagePickerControllerOriginalImage] resizedImage:CGSizeMake(320, 460) interpolationQuality:1];
		flyerFront.image = bacchanal.flyerSideOne ;
	}
	else{
		bacchanal.flyerSideTwo = [[info objectForKey:UIImagePickerControllerOriginalImage] resizedImage:CGSizeMake(320, 460) interpolationQuality:1];
		flyerBack.image = bacchanal.flyerSideTwo;
		
	}
}

-(IBAction)pickDate:(id)sender{
	
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];	
	
	if ([startDate isFirstResponder]) {
		[startDate setText:[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:datePicker.date]]];
	}
	else {
		[endDate setText:[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:datePicker.date]]];
	}
	
	[dateFormat release];
	
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

// Implement viewDidLoad to do additional setup after loading the view, typically from a ni
- (void)viewDidLoad {
	[super viewDidLoad];
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelSubmit:)] autorelease];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(submitEvent:)] autorelease];
	
	
	scrollView.frame = CGRectMake(0, 0, 320, 416);
	[scrollView setContentSize:CGSizeMake(320, 550)];
	
	[startDate setInputView:datePicker];
	[endDate setInputView:datePicker];
	[datePicker setDatePickerMode:UIDatePickerModeDateAndTime];
}

-(void) viewWillAppear:(BOOL)animated {    
	//---registers the notifications for keyboard---
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidShow:)
												 name:UIKeyboardDidShowNotification
											   object:self.view.window];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidHide:)
												 name:UIKeyboardDidHideNotification
                                               object:nil];
}

//---when a TextField view begins editing---
-(void) textFieldDidBeginEditing:(UITextField *)textFieldView {  
	currentTextField = textFieldView;
} 

-(void)textViewDidBeginEditing:(UITextView *)textView{
	currentTextView = textView;
}

-(BOOL) textFieldShouldReturn:(UITextField *) textFieldView {  
	[textFieldView resignFirstResponder];
	return YES;
}

//---when a TextField view is done editing---
-(void) textFieldDidEndEditing:(UITextField *) textFieldView {  
	currentTextField = nil;
}

-(void)textViewDidEndEditing:(UITextView *)textView{
	currentTextView = nil;
}

//---when the keyboard appears---
-(void) keyboardDidShow:(NSNotification *) notification {
	if (keyboardIsShown) return;
	
	NSDictionary* info = [notification userInfo];
	
	//---obtain the size of the keyboard---
	NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
    
	//---resize the scroll view (with keyboard)---
	CGRect viewFrame = [scrollView frame];
	viewFrame.size.height -= keyboardSize.height;
	scrollView.frame = viewFrame;
	
	//---scroll to the current text field---
	if (currentTextField != nil){
		
		CGRect textFieldRect = [currentTextField frame];
		[scrollView scrollRectToVisible:textFieldRect animated:YES];
	}
	
	if (currentTextView != nil){
		CGRect textViewRect = [currentTextView frame];
		[scrollView scrollRectToVisible:textViewRect animated:YES];
	}
	
	keyboardIsShown = YES;
}


//---when the keyboard disappears---
-(void) keyboardDidHide:(NSNotification *) notification {
	NSDictionary* info = [notification userInfo];
	
	//---obtain the size of the keyboard---
	NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
	
	//---resize the scroll view back to the original size (without keyboard)---
	CGRect viewFrame = [scrollView frame];
	viewFrame.size.height += keyboardSize.height;
	scrollView.frame = viewFrame;
	
	keyboardIsShown = NO;
}

-(void) viewWillDisappear:(BOOL)animated {
	//---removes the notifications for keyboard---
	[[NSNotificationCenter defaultCenter]
	 removeObserver:self
	 name:UIKeyboardWillShowNotification
	 object:nil];
	[[NSNotificationCenter defaultCenter]
	 removeObserver:self
	 name:UIKeyboardWillHideNotification
	 object:nil];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
	[super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
	[super viewDidUnload];
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[datePicker release];
	[eventNotes release];
	[startDate release];
	[endDate release];
	[flyerFront release];
	[flyerBack release];
	[addFlyer release];
	[scrollView release];
	[eventName release];
	[eventLocation release];
	[super dealloc];
}


@end
